package com.lab.book.sharding.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lab.book.sharding.entity.Address;
import com.lab.book.sharding.entity.Order;
import com.lab.book.sharding.entity.OrderItem;
import com.lab.book.sharding.mapper.AddressMapper;
import com.lab.book.sharding.mapper.OrderItemMapper;
import com.lab.book.sharding.mapper.OrderMapper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private OrderItemMapper orderItemMapper;

	@Autowired
	private AddressMapper addressMapper;

	public void initAddressTable() throws SQLException {
		for (int i = 1; i <= 10; i++) {
			Address entity = new Address();
			entity.setAddressId((long) i);
			entity.setAddressName("address_" + String.valueOf(i));
			addressMapper.insert(entity);
		}
	}

	public List<Long> insertData() throws SQLException {
		log.info("---------------------------- Insert Data ----------------------------");
		List<Long> result = new ArrayList<Long>(10);
		for (int i = 1; i <= 10; i++) {
			Order order = new Order();
			order.setUserId(i);
			order.setAddressId(i);
			order.setStatus("INSERT_TEST");
			orderMapper.insert(order);

			OrderItem item = new OrderItem();
			item.setOrderId(order.getOrderId());
			item.setUserId(i);
			item.setStatus("INSERT_TEST");
			orderItemMapper.insert(item);
			result.add(order.getOrderId());
		}
		return result;
	}

	public void deleteData(final List<Long> orderIds) throws SQLException {
		log.info("---------------------------- Delete Data ----------------------------");
		for (Long each : orderIds) {
			orderMapper.delete(each);
			orderItemMapper.delete(each);
		}
	}

	public void printData() throws SQLException {
		log.info("---------------------------- Print Order Data -----------------------");
		for (Object each : orderMapper.selectAll()) {
			System.out.println(each);
		}
		log.info("---------------------------- Print OrderItem Data -------------------");
		for (Object each : orderItemMapper.selectAll()) {
			System.out.println(each);
		}
	}

}
